package com.df.gateway.handler;

import com.alibaba.fastjson2.JSON;
import com.df.base.other.R;
import com.df.base.other.RpcReq;
import com.df.gateway.utils.DubboUtils;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.util.HashMap;
import java.util.Map;

@ChannelHandler.Sharable
public class GatewayHttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接注册");
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("连接取消注册");
        super.channelUnregistered(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest o) throws Exception {
        String uri = o.uri();
        System.out.println("收到请求："+ uri);
        //TODO 消息方案2：根据 服务名，功能名，方法名，版本  按指定算法生成唯一id，收到消息后再反解析
        //http请求都用post
        //解析参数 eg: 格式：/{服务名}/{服务里具体的功能块名}/{业务名(一般为方法名)}/{版本} /Account/User/Login/1.0.0
        //解析参数 eg: 格式2：/{服务名映射的short值}/{请求路径的hash值}/{代码版本} /1/3541256/1.0.0
        String[] split = uri.split("/");
        boolean ok = true;
        R r = new R();
        if(split.length<5){
            ok = false;
        }
        if(ok){
            byte[] bodyBytes = new byte[o.content().readableBytes()];
            o.content().readBytes(bodyBytes);

            RpcReq req = new RpcReq();
//            req.setPlayerId();
//            req.setPath();
            req.setBody(bodyBytes);

            //其他业务参数，路径的参数和post的body参数
            //http请求则使用1问1答同步等待即可
            r = DubboUtils.rpc(split[1],split[4],req);

            //TODO 返回值后处理 记录日志，消息进一步处理了等
        }else {
            r.setCode(4001);
            r.setMsg("请求地址不存在");
        }

        String msg = JSON.toJSONString(r);


        // 创建http响应
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
        // 设置头信息
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
